package com.ld.explanation;

import com.intellij.openapi.editor.Editor;
import com.ld.lang.LangOptions;
import com.ld.translation.library.trans.LANG;
import com.ld.translation.library.trans.factory.TFactory;
import com.ld.translation.library.trans.factory.TranslatorFactory;
import com.ld.utils.CommonUtils;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class TextExplanation {

    private final static String ZH = "ZH";
    private final static String EN = "EN";
    private final static String NULL = "NULL";

    public final static String splicing = "auto";

    private static List<String> skipCharacters = Arrays.asList(",","_","-",".","=");

    public static Map<String,String> translationCache = new HashMap<>();

    public Editor editor;

    public static TextExplanation getTextExplanation(Editor editor){
        String selectedText = editor.getSelectionModel().getSelectedText();
        TextExplanation textExplanation = null;
        switch (explanation(selectedText)){
            case ZH:
                textExplanation = new ZHExplanation(editor);
                break;
            case EN:
                textExplanation = new ENExplanation(editor);
                break;
            case NULL:
                break;
                default:
        }
        return textExplanation;
    }

    public abstract String translation();

    public String zhToEn(String v) throws Exception {
        TFactory factory = new TranslatorFactory();
        String google = factory.get("google").trans(LANG.ZH, LANG.EN, v);
        return google;
    }

    public String enToZh(String v) throws Exception {
        TFactory factory = new TranslatorFactory();
        String google = factory.get("google").trans(LANG.EN, LANG.ZH, v);
        return google;
    }

    private static String explanation(String selectedText){
        if (selectedText != null && selectedText.trim().length() > 0){
            int zh = 0;
            int en = 0;
            int length = selectedText.length();
            for (int i = 0; i < length; i++) {
                String trim = String.valueOf(selectedText.charAt(i)).trim();
                if (trim.length() == 0 || skipCharacters.contains(trim)){
                    continue;
                }
                if (CommonUtils.isMatch("[a-zA-Z]",trim)){
                    ++en;
                }else {
                    ++zh;
                }
            }
            if (zh > en){
                return ZH;
            }else {
                return EN;
            }
        }else {
            return NULL;
        }
    }

    public String getSelectedText(){
        return editor.getSelectionModel().getSelectedText().trim();
    }
}
